﻿using System.Web.Mvc;
using System.Linq;

namespace SlamCms.Web.Sitemaps
{
	// TODO This class should only be an instance per request because the current node won't change and can be reused
	public class SitemapHtmlHelper
	{
		private readonly SlamCmsHtmlHelper _slamCmsHtmlHelper;
		private readonly Sitemap _sitemap;
		private SitemapNode _currentNode;

		public SitemapHtmlHelper(SlamCmsHtmlHelper slamCmsHtmlHelper, Sitemap sitemap)
		{
			_slamCmsHtmlHelper = slamCmsHtmlHelper;
			_sitemap = sitemap;
		}

		public SlamCmsHtmlHelper SlamCms
		{
			get
			{
				return _slamCmsHtmlHelper;	
			}
		}

		public HtmlHelper Html
		{
			get
			{
				return _slamCmsHtmlHelper.Html;
			}
		}
		
		public Sitemap Sitemap
		{
			get
			{
				return _sitemap;
			}
		}

		public SitemapNode CurrentNode
		{
			get
			{
				if (_currentNode == null)
					_currentNode = GetCurrentNode();

				return _currentNode;
			}
		}

		public bool IsCurrentNode(SitemapNode node)
		{
			return node == CurrentNode;
		}

		public bool IsSelected(SitemapNode node)
		{
			var breadcrumb = CurrentNode.GetBreadcrumb();
			return breadcrumb.Any(n => n == node);
		}

		public BreadcrumbHtmlHelper Breadcrumb()
		{
			return new BreadcrumbHtmlHelper(this);
		}

		public MenuHtmlHelper Menu()
		{
			return new MenuHtmlHelper(this);
		}

		protected SitemapNode GetCurrentNode()
		{
			var url = Html.ViewContext.HttpContext.Request.RawUrl;
			var result = _sitemap.FindNodes(n => url.StartsWith(n.Url))
									  .OrderByDescending(n => n.Depth)
									  .ThenByDescending(n => n.Url.Length)
									  .FirstOrDefault();
			
			return result;
		}
	}
}
